package com.huiquan.analysis.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.huiquan.foundation.constant.BusinessContants;
import com.huiquan.foundation.dao.CheckParamDao;
import com.huiquan.foundation.domain.CheckParam;
import com.huiquan.framework.base.BaseService;
import com.huiquan.framework.dao.EmailDao;
import com.huiquan.framework.utils.EMailUtil;
import com.huiquan.management.constant.MigrateCode;

/**
 * 词典 service
 *
 * @author leo
 * @time 2017年4月11日 下午5:42:27
 */
@Service
public class AnalysisCheckExportFileService extends BaseService {

	@Autowired
	private CheckParamDao checkParamDao;
	@Value("${migrate.bak.file.path.pre}")
	private String analysisCheckFilePath;
	@Autowired
	private EmailDao emailDao;
	@Autowired
	private EMailUtil eMailUtil;

	/*
	 * 校验导出的主诉现病史等文件
	 * 
	 */
	public void checkAnalysisFile() {
		LOGGER.info("check analysis file export beggin!");
		List<CheckParam> allCheck = checkParamDao.retrieveList();
		Iterator<CheckParam> it = allCheck.iterator();
		// 过滤不需要校验的type
		while (it.hasNext()) {
			CheckParam check = it.next();
			if (!check.getType().contains("NEW_TRAIN")) {
				it.remove();
			}
		}
		Calendar calendar = Calendar.getInstance(); // 得到日历
		calendar.setTime(new Date());// 把当前时间赋给日历
		calendar.add(Calendar.DAY_OF_MONTH, -1);// 提前一天的文件
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String createdate = sdf.format(calendar.getTime());
		StringBuffer errDescription = new StringBuffer();
		for (CheckParam check : allCheck) {
			String type = check.getType();
			// 根据type来找文件放的位置
			String[] typeSplit = type.split("_", 2);
			String moduleName = typeSplit[0];

			String bakFilePath = analysisCheckFilePath + File.separator + moduleName.toLowerCase();
			if (typeSplit.length > 1) {
				bakFilePath += File.separator + typeSplit[1].toLowerCase();
			}
			File file = new File(bakFilePath + File.separator + createdate);
			if (file != null && file.exists()) {
				if (!file.isDirectory()) {
					if (file.length() < Long.parseLong(check.getParam())) {
						// 文件减少,文件有误,发送邮件
						errDescription.append(check.getDescription()).append(";");
					} else {
						// 更新此次文件大小到param字段
						check.setParam(file.length() + "");
						checkParamDao.update(check);
					}
				}
			}
		}
		if (errDescription != null && errDescription.length() > 0) {
			LOGGER.info("analysis导出的文件大小减小,请检查"+errDescription.toString());
			sendMail(errDescription.toString());
		}
		LOGGER.info("check analysis file export end!");
	}

	private void sendMail(String string) {
		LOGGER.error("CheckAnalysisFile error:" + string);

		// 报错后发邮件通知
		List<String> address = emailDao.retrieveAddressList(BusinessContants.SEND_EMAIL_GROUP_DATA_RUNNING_ERROR);
		String subject = "标注系统analysis导出文件检查该文件减小：" + string;
		if (!address.isEmpty()) {
			try {
				eMailUtil.sendBatchEmail("", subject, address);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}

	}

	/**
	 * 初始化主诉现病史检查记录
	 */
	public void initAnalysisCheckParam() {
		List<CheckParam> allCheck = checkParamDao.retrieveList();
		List<String> typeList = new ArrayList<>();
		for (CheckParam check : allCheck) {
			if (!typeList.contains(check.getType())) {
				typeList.add(check.getType());
			}
		}
		for (MigrateCode mc : MigrateCode.values()) {
			if (mc.name().contains("NEW_TRAIN")) {
				init(mc, typeList);
			}
		}
	}

	private void init(MigrateCode mc, List<String> typeList) {
		if (!typeList.contains(mc.name())) {
			CheckParam value = new CheckParam();
			value.setType(mc.name());
			value.setParam(0 + "");
			value.setDescription(mc.getDesc());
			checkParamDao.insert(value);
		}
	}

}
